package models

import (
	"github.com/zw2582/ginlib"
	"time"
)

type BankData struct {
	Id int `xorm:"pk autoincr"`
	Name string `xorm:"varchar(32) notnull"`
	BankCardNo string `xorm:"varchar(25) unique notnull comment('银行卡卡号')"`
	IdCardNo string `xorm:"varchar(32) notnull"`
	Phone string `xorm:"varchar(15) notnull"`
	CreatedAt time.Time `xorm:"created"`
	UpdatedAt time.Time `xorm:"updated"`
}

func init()  {
	ginlib.XormAddWaitSync(new(BankData))
}

func (this *BankData) Save() {
	if this.Id == 0 {
		if this.BankCardNo == "" {
			panic("请传递银行卡号")
		}
		obj := BankDataGetByBankCardNo(this.BankCardNo)
		this.Id = obj.Id
	}

	var err error
	if this.Id == 0 {
		_, err = DB.Insert(this)
	} else {
		_, err = DB.ID(this.Id).Update(this)
	}

	if err != nil {
		panic(err)
	}
}

func BankDataGetByBankCardNo(bankCardNo string) (obj BankData) {
	DB.Where("bank_card_no=?", bankCardNo).Get(&obj)
	return
}

//BankDataSave 同步保存卡信息
func BankDataSave(name, bankCardNo, idCardNo, phone string)  {
	if bankCardNo == "" {
		return
	}
	obj := BankDataGetByBankCardNo(bankCardNo)
	obj.BankCardNo = bankCardNo
	if obj.Name != name && name != "" {
		obj.Name = name
	}
	md5IdCardNo := ginlib.Md5encode(idCardNo)
	if obj.IdCardNo != md5IdCardNo && idCardNo != "" {
		obj.IdCardNo = md5IdCardNo
	}
	if obj.Phone != phone && phone != "" {
		obj.Phone = phone
	}
	var err error
	if obj.Id == 0 {
		_, err = DB.Insert(&obj)
	} else {
		_, err = DB.ID(obj.Id).Update(&obj)
	}

	if err != nil {
		panic(err)
	}
}

//BankDataCheck 银行卡本地校验
func BankDataCheck(name, bankCardNo, idCardNo, phone string) (rc ResultCode) {
	if bankCardNo == "" {
		return nil
	}
	obj := BankDataGetByBankCardNo(bankCardNo)
	if obj.Id == 0 {
		return nil
	}
	//超过半个月的也不校验
	//if time.Now().Sub(obj.UpdatedAt) > time.Hour*24*15 {
	//	return nil
	//}
	//需要姓名校验
	if name != "" {
		if obj.Name == "" {
			return nil
		}
		if obj.Name != name {
			rc = RC_BANK_NOT_YIZHI
			return
		} else {
			rc = RC_BANK_YIZHI
		}
	}
	//需要身份证校验
	if idCardNo != "" {
		if obj.IdCardNo == "" {
			return nil
		}
		if obj.IdCardNo != ginlib.Md5encode(idCardNo) {
			rc = RC_BANK_NOT_YIZHI
			return
		} else {
			rc = RC_BANK_YIZHI
		}
	}
	//需要手机号码校验
	if phone != "" {
		if obj.Phone == "" {
			return nil
		}
		if obj.Phone != phone {
			rc = RC_BANK_NOT_YIZHI
			return
		} else {
			rc = RC_BANK_YIZHI
		}
	}
	return
}